import { Button, Form, Input, Modal } from 'antd'
import './index.less'
import { useEffect, useRef, useState } from 'react'
import makeCode from '@/utils/makeCode'
import { useRequest } from 'ahooks'
import { login, LoginParams, LoginType } from './services'
import { useModel, useSearchParams } from '@umijs/max'
import { cleanMenuData, getInitData } from '@/utils/getMenuInfo'
import { MenuAll } from '@/services/common'

type FormValues = LoginParams & {
  smsCode: string
}

const LoginPage: React.FC = () => {
  const [smsCode, setSmsCode] = useState<string>()
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const { runAsync, loading } = useRequest(login, {manual: true})
  const hrefParams = useSearchParams()
  const { setInitialState } = useModel('@@initialState')
  const { removeAll } = useModel('global')

  const onFinish = (values: FormValues) => {
    if (values.smsCode.toLowerCase() !== smsCode) {
      Modal.error({
        title: '错误',
        content: '验证码错误',
      })
      return
    }
    runAsync({...values, loginType: LoginType.管理员登录})
    .then(res => {
      const { data } = res
      localStorage.setItem('userId', data.userId)
      localStorage.setItem('username', data.userName)
      localStorage.setItem('userType', String(LoginType.管理员登录))
      sessionStorage.setItem('userId', data.userId)
      sessionStorage.setItem('username', data.userName)
      sessionStorage.setItem('userType', String(LoginType.管理员登录))
      localStorage.setItem('Authorization', data.token)
      getInitData(MenuAll.平台可见菜单).then(res => {
        if (res) {
          const menuList = cleanMenuData(res[0].data)
          setInitialState({
            menuList,
          })
          location.href = hrefParams[0].get('redirect') || '/'
        }
      })
    })
  }

  const onFinishFailed = ({ errorFields }: ValidateErrorEntity<FormValues>) => {
    if (errorFields.length) {
      Modal.error({
        title: '错误',
        content: errorFields[0].errors[0],
      })
    }
  }

  const refreshCode = () => {
    if (canvasRef.current) {
      setSmsCode(makeCode(canvasRef.current))
    }
  }

  useEffect(() => {
    refreshCode()
    removeAll()
  }, []);

  return <div className="login-container">
    <div className="login-card">
      <div className="logo">
        <img src='https://homechargesmall.liaoqianapp.com/img/login-logo.png' />
      </div>
      <div className="title">家苑充电管理系统</div>
      <Form<FormValues> className="form" onFinish={onFinish} onFinishFailed={onFinishFailed}>
        <Form.Item name='username' rules={[{required: true, message: '请输入账号'}]} noStyle>
          <Input placeholder='账号' className='input' />
        </Form.Item>
        <Form.Item name='password' rules={[{required: true, message: '请输入密码'}]} noStyle>
          <Input.Password placeholder='密码' className='input' />
        </Form.Item>
        <div className='smsCode-cell'>
          <Form.Item name='smsCode' rules={[{required: true, message: '请输入验证码'}]} noStyle>
            <Input placeholder='验证码' className='input' />
          </Form.Item>
          <div className="smsCode" onClick={refreshCode}>
            <canvas ref={canvasRef} />
          </div>
        </div>
        <div className="submit">
          <Button type='primary' htmlType='submit' loading={loading}>立即登录</Button>
        </div>
      </Form>
    </div>
  </div>
}

export default LoginPage
